<template>
  <div class="video-container">
    <div class="main-content">
      <div class="selection-panel">
        <h2>视频资源生成配置</h2>
        
        <!-- 教学阶段选择 -->
        <div class="form-item">
          <label>教学阶段</label>
          <el-select v-model="formData.grade" placeholder="请选择教学阶段" @change="handleStageChange">
            <el-option
              v-for="item in stages"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 教学科目选择 -->
        <div class="form-item">
          <label>教学科目</label>
          <el-select v-model="formData.subject" placeholder="请选择教学科目">
            <el-option
              v-for="item in subjects"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </div>

        <!-- 视频提示词输入 -->
        <div class="form-item">
          <label>视频提示词</label>
          <el-input
            v-model="formData.topic"
            type="textarea"
            :rows="4"
            placeholder="请输入视频主题"
          />
        </div>

        <!-- 视频模型选择 -->
        <div class="form-item">
          <label>视频模型</label>
          <el-select v-model="formData.model" placeholder="请选择视频模型">
            <el-option label="wanx2.1-t2v-turbo (生成速度更快，表现均衡)" value="wanx2.1-t2v-turbo" />
            <el-option label="wanx2.1-t2v-plus (生成细节更丰富，画面更具质感)" value="wanx2.1-t2v-plus" />
          </el-select>
        </div>

        <!-- 视频尺寸选择 -->
        <div class="form-item">
          <label>视频尺寸</label>
          <el-select v-model="formData.size" placeholder="请选择视频尺寸">
            <el-option label="1280*720 (720P)" value="1280*720" />
            <el-option label="624*624 (480P)" value="624*624" />
          </el-select>
        </div>

        <!-- 视频风格选择 -->
        <div class="form-item">
          <label>视频风格</label>
          <el-select v-model="formData.style" placeholder="请选择视频风格">
            <el-option label="动画风格" value="animation" />
            <el-option label="实拍风格" value="live" />
            <el-option label="混合风格" value="mixed" />
          </el-select>
        </div>

        <!-- 视频时长选择 -->
        <div class="form-item">
          <label>视频时长（秒）</label>
          <el-input-number 
            v-model="formData.duration" 
            :min="1" 
            :max="30" 
            :step="1"
            placeholder="请输入视频时长"
          />
        </div>
      </div>

      <div class="action-panel">
        <el-button type="primary" @click="generateVideo" :loading="generating">
          <el-icon><VideoCamera /></el-icon>
          生成视频
        </el-button>
      </div>

      <div v-if="videoList.length > 0" class="video-list">
        <h2>生成的视频</h2>
        <div v-for="(video, index) in videoList" :key="index" class="video-item">
          <div class="video-preview">
            <div class="video-wrapper">
              <template v-if="video.status === 'PENDING' || video.status === 'PROCESSING' || video.status === 'RUNNING'">
                <div class="video-placeholder">
                  <el-icon class="loading-icon"><Loading /></el-icon>
                  <span>视频生成中...</span>
                </div>
              </template>
              <template v-else-if="video.status === 'FAILED'">
                <div class="video-placeholder error">
                  <el-icon><WarningFilled /></el-icon>
                  <span>生成失败</span>
                </div>
              </template>
              <template v-else>
                <el-image 
                  :src="video.thumbnail || getDefaultVideoThumbnail()" 
                  fit="cover" 
                  @error="(e) => handleImageError(e, video)"
                >
                  <template #error>
                    <div class="video-placeholder">
                      <el-icon><VideoPlay /></el-icon>
                      <span>点击播放视频</span>
                    </div>
                  </template>
                </el-image>
              </template>
              <div v-if="video.url" class="video-actions">
                <el-button 
                  type="primary" 
                  circle 
                  @click="previewVideo(video)"
                  :icon="VideoPlay"
                />
                <el-button 
                  type="success" 
                  circle 
                  @click="handleDownload(video)"
                  :icon="Download"
                />
              </div>
            </div>
          </div>
          <div class="video-info">
            <h3>{{ video.title }}</h3>
            <p>{{ video.description }}</p>
            <div class="video-meta">
              <span>时长：{{ video.duration }}</span>
              <span>尺寸：{{ video.size }}</span>
              <span>模型：{{ video.model }}</span>
              <span>
                状态：
                <el-tag 
                  :type="video.status === 'SUCCEEDED' ? 'success' : 
                        video.status === 'FAILED' ? 'danger' : 
                        'warning'"
                  size="small"
                >
                  {{ video.status === 'SUCCEEDED' ? '已完成' : 
                      video.status === 'FAILED' ? '失败' : 
                      '处理中' }}
                </el-tag>
              </span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 视频预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="视频预览"
      width="80%"
      :close-on-click-modal="false"
      class="video-preview-dialog"
    >
      <div class="preview-content">
        <div v-if="!previewLoaded && previewLoading" class="preview-loading">
          <el-icon class="loading-icon"><Loading /></el-icon>
          <span>视频加载中...</span>
        </div>
        <div v-if="previewError" class="preview-error">
          <el-icon><WarningFilled /></el-icon>
          <p>{{ previewErrorMessage }}</p>
          <el-button type="primary" @click="retryPreview">重试</el-button>
        </div>
        <video 
          v-show="!previewError"
          ref="videoPlayer"
          :src="previewUrl" 
          controls
          class="preview-video"
          @error="handleVideoError"
          @loadeddata="previewLoaded = true; previewLoading = false"
          @loadstart="previewLoading = true"
        ></video>
      </div>
    </el-dialog>

    <!-- 任务状态对话框 -->
    <el-dialog
      v-model="taskStatusVisible"
      title="视频生成任务"
      width="30%"
      :close-on-click-modal="false"
      class="task-status-dialog"
    >
      <div class="task-status-content">
        <el-progress 
          :percentage="taskProgress" 
          :status="taskStatus === 'SUCCEEDED' ? 'success' : taskStatus === 'FAILED' ? 'exception' : ''"
        />
        <div class="task-status-text">
          {{ taskStatusText }}
        </div>
        <div v-if="taskStatus === 'SUCCEEDED'" class="task-actions">
          <el-button type="primary" @click="viewGeneratedVideo">查看视频</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, onUnmounted } from 'vue'
import { ElMessage } from 'element-plus'
import axios from 'axios'
import { 
  downloadVideo, 
  previewVideo as importedPreviewVideo,
  generateVideo as importedGenerateVideo,
  createWanxVideoTask,
  getWanxVideoTaskStatus
} from '@/api/VideoAI'
import { Download, VideoPlay, VideoCamera, Loading, WarningFilled } from '@element-plus/icons-vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 表单数据
const formData = ref({
  subject: '',
  grade: '',
  topic: '',
  description: '',
  duration: 5
})

// 选项数据
const stages = ref([
  { value: 'primary', label: '小学' },
  { value: 'junior', label: '初中' },
  { value: 'senior', label: '高中' },
  { value: 'university', label: '大学' }
])

// 模拟科目数据
const subjectsMap = {
  primary: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' }
  ],
  junior: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' }
  ],
  senior: [
    { value: 'math', label: '数学' },
    { value: 'chinese', label: '语文' },
    { value: 'english', label: '英语' },
    { value: 'physics', label: '物理' },
    { value: 'chemistry', label: '化学' },
    { value: 'biology', label: '生物' }
  ],
  university: [
    { value: 'math', label: '高等数学' },
    { value: 'physics', label: '大学物理' },
    { value: 'chemistry', label: '大学化学' }
  ]
}

const subjects = ref([])

// 视频相关
const videoList = ref([])

// 视频预览相关
const previewVisible = ref(false)
const previewUrl = ref('')
const previewTitle = ref('')
const previewLoading = ref(false)
const previewLoaded = ref(false)
const previewError = ref(false)
const previewErrorMessage = ref('')
const videoPlayer = ref(null)
const previewItem = ref(null)

// 任务状态相关
const taskStatusVisible = ref(false)
const taskStatus = ref('PENDING')
const taskProgress = ref(0)
const taskId = ref('')
const generating = ref(false)
const taskStatusText = computed(() => {
  switch (taskStatus.value) {
    case 'PENDING':
      return '任务已创建，等待处理中...'
    case 'PROCESSING':
      return '视频生成中，请耐心等待...'
    case 'SUCCEEDED':
      return '视频生成成功！'
    case 'FAILED':
      return '视频生成失败，请重试'
    default:
      return '未知状态'
  }
})

// 添加轮询计数和最大轮询次数
const pollCount = ref(0)
const maxPollCount = ref(30) // 最多轮询30次，约15分钟

// 处理教学阶段变化
const handleStageChange = (value) => {
  formData.value.subject = ''
  subjects.value = subjectsMap[value] || []
}

// 处理视频URL，转换为正确的API格式
const normalizeVideoUrl = (url) => {
  if (!url) return url;
  
  // 如果已经是API格式，直接返回
  if (url.startsWith('/api/')) return url;
  
  // 检查URL是否为裸视频ID或UUID格式
  if (!url.startsWith('http')) {
    // 如果是简单的UUID或ID，转换为API请求格式
    if (url.includes('-') || /^[0-9a-f]{8}/.test(url)) {
      return `/api/media-resources/video/${url}`
    } else {
      return `/api/media-resources/video/id/${url}`
    }
  }
  
  // 处理直接本地服务器链接(不带/api前缀)
  if (url.startsWith('http://localhost:8080/') && !url.includes('/api/')) {
    // 提取ID部分
    const id = url.split('/').pop()
    if (id) {
      return `/api/media-resources/video/${id}`
    }
  }
  
  return url;
}

// 生成视频
const generateVideo = async () => {
  if (!formData.value.grade) {
    ElMessage.warning('请选择教学阶段')
    return
  }
  if (!formData.value.subject) {
    ElMessage.warning('请选择教学科目')
    return
  }
  if (!formData.value.topic) {
    ElMessage.warning('请输入视频主题')
    return
  }
  if (!formData.value.duration) {
    formData.value.duration = 3 // 默认3秒
  }
  if (!formData.value.size) {
    formData.value.size = '1280*720' // 默认720P
  }
  if (!formData.value.model) {
    formData.value.model = 'wanx2.1-t2v-turbo' // 默认模型
  }

  generating.value = true
  taskStatusVisible.value = true
  taskStatus.value = 'PENDING'
  taskProgress.value = 0

  try {
    // 获取科目标签
    const subjectItem = subjects.value.find(item => item.value === formData.value.subject)
    const subjectLabel = subjectItem ? subjectItem.label : formData.value.subject
    
    // 获取阶段标签
    const stageItem = stages.value.find(item => item.value === formData.value.grade)
    const stageLabel = stageItem ? stageItem.label : formData.value.grade

    // 构建请求数据
    const requestData = {
      subject: subjectLabel,
      grade: stageLabel,
      topic: formData.value.topic,
      description: formData.value.description || `为${stageLabel}年级${subjectLabel}科目的'${formData.value.topic}'主题创建一个教学视频。${formData.value.topic}`,
      duration: formData.value.duration,
      size: formData.value.size,
      model: formData.value.model
    }

    console.log('发送视频生成请求:', requestData)

    // 发送生成请求
    const response = await importedGenerateVideo(requestData)
    console.log('视频生成API响应:', response)
    
    if (response && response.data) {
      // 提取taskId，可能在不同的位置
      taskId.value = response.data.taskId || response.data.id || response.data.url
      
      // 如果返回的是URL而不是taskId，则是任务ID字符串
      if (typeof taskId.value === 'string' && !taskId.value.includes('/')) {
        // 添加一个临时的视频对象到列表，显示处理中状态
        const tempVideo = {
          id: response.data.id || Date.now(),
          taskId: taskId.value,
          title: formData.value.topic,
          description: requestData.description,
          status: 'PENDING',
          duration: formData.value.duration + '秒',
          size: formData.value.size,
          model: formData.value.model
        }
        
        videoList.value.unshift(tempVideo)
        
        // 开始轮询任务状态
        pollTaskStatus()
        
        ElMessage.success('视频生成任务已创建，请等待处理完成')
      } else if (response.data.url) {
        // 直接返回了URL
        taskStatus.value = 'SUCCEEDED'
        taskProgress.value = 100
        
        // 处理视频URL，确保格式正确
        const normalizedUrl = normalizeVideoUrl(response.data.url)
        
        const newVideo = {
          id: response.data.id || Date.now(),
          title: formData.value.topic,
          description: requestData.description,
          url: normalizedUrl,
          status: 'SUCCEEDED',
          duration: formData.value.duration + '秒',
          size: formData.value.size,
          model: formData.value.model
        }
        
        videoList.value.unshift(newVideo)
        ElMessage.success('视频生成成功！')
        
        // 5秒后关闭对话框
        setTimeout(() => {
          taskStatusVisible.value = false
        }, 5000)
      } else {
        ElMessage.warning('视频任务已创建，但未返回任务ID或URL，无法跟踪进度')
        taskStatusVisible.value = false
      }
    } else {
      ElMessage.error('生成视频失败')
      taskStatusVisible.value = false
    }
  } catch (error) {
    console.error('生成视频失败:', error)
    ElMessage.error('生成视频失败: ' + (error.response?.data?.message || error.message))
    taskStatusVisible.value = false
  } finally {
    generating.value = false
  }
}

// 轮询任务状态
const pollTaskStatus = async () => {
  if (!taskId.value) return
  
  // 增加轮询计数
  pollCount.value++
  
  // 检查是否超过最大轮询次数
  if (pollCount.value > maxPollCount.value) {
    ElMessage.warning(`视频生成超时，请稍后在历史记录中查看。任务ID: ${taskId.value}`)
    taskStatus.value = 'TIMEOUT'
    taskProgress.value = 100
    
    // 更新列表中的视频状态
    const existingVideo = videoList.value.find(v => v.taskId === taskId.value || v.id === taskId.value)
    if (existingVideo) {
      existingVideo.status = 'TIMEOUT'
      existingVideo.statusMessage = '生成超时，可稍后刷新查看'
    }
    
    // 3秒后关闭对话框
    setTimeout(() => {
      taskStatusVisible.value = false
    }, 3000)
    return
  }
  
  try {
    const response = await getWanxVideoTaskStatus(taskId.value)
    console.log(`轮询视频任务状态(${pollCount.value}/${maxPollCount.value}):`, response)
    
    if (response.data) {
      // 更新任务状态，确保从正确的位置获取
      const responseStatus = response.data.status || 
                           response.data.output?.task_status || 
                           response.data.result?.task_status ||
                           'PENDING'
      
      taskStatus.value = responseStatus
      
      // 根据状态更新进度
      if (taskStatus.value === 'PENDING') {
        taskProgress.value = 10
        // 延长轮询间隔到10秒
        setTimeout(pollTaskStatus, 10000)
      } else if (taskStatus.value === 'PROCESSING' || taskStatus.value === 'RUNNING') {
        // 根据轮询次数增加进度，给用户更好的反馈
        taskProgress.value = 50 + Math.min(30, pollCount.value * 2)
        // 延长轮询间隔到15秒
        setTimeout(pollTaskStatus, 15000)
      } else if (taskStatus.value === 'SUCCEEDED') {
        taskProgress.value = 100
        
        // 对于已完成状态，等待更长时间确保视频已完全生成并可用
        setTimeout(async () => {
          try {
            // 从后端获取生成的视频信息，确保视频已完全处理完毕
            const videoResponse = await getWanxVideoTaskStatus(taskId.value, true)
            console.log('获取到视频结果:', videoResponse)
            
            // 尝试从多种可能的响应格式中提取URL
            const videoUrl = extractVideoUrl(videoResponse.data)
            
            if (videoUrl) {
              // 处理视频URL，确保格式正确
              const normalizedUrl = normalizeVideoUrl(videoUrl)
              
              // 更新现有视频列表中的对象
              const existingVideo = videoList.value.find(v => v.taskId === taskId.value || v.id === taskId.value)
              if (existingVideo) {
                existingVideo.url = normalizedUrl
                existingVideo.thumbnail = videoResponse.data.thumbnailUrl || videoResponse.data.output?.thumbnail_url || ''
                existingVideo.status = 'SUCCEEDED'
              } else {
                // 添加新的视频对象
                const newVideo = {
                  id: videoResponse.data.id || taskId.value,
                  taskId: taskId.value,
                  title: formData.value.topic,
                  description: formData.value.description || formData.value.topic,
                  thumbnail: videoResponse.data.thumbnailUrl || videoResponse.data.output?.thumbnail_url || '',
                  url: normalizedUrl,
                  status: 'SUCCEEDED',
                  duration: formData.value.duration + '秒',
                  size: formData.value.size || '1280*720',
                  model: formData.value.model || 'wanx2.1-t2v-turbo'
                }
                videoList.value.unshift(newVideo)
              }
              ElMessage.success('视频生成成功！')
              
              // 为视频设置一个标记，提示用户需要等待一段时间才能播放
              setTimeout(() => {
                const existingVideo = videoList.value.find(v => v.taskId === taskId.value || v.id === taskId.value)
                if (existingVideo) {
                  existingVideo.readyForPlay = true
                }
              }, 10000) // 再等待10秒才标记为可播放
            } else {
              console.warn('视频已生成但URL不可用:', videoResponse)
              // 如果轮询次数未达上限，尝试再次轮询获取URL
              if (pollCount.value < maxPollCount.value) {
                setTimeout(pollTaskStatus, 10000)
                return
              } else {
                ElMessage.warning('视频生成可能成功，但无法获取视频URL，请稍后再试')
              }
            }
          } catch (videoError) {
            console.error('获取视频信息失败:', videoError)
            ElMessage.warning('视频已生成，但获取下载链接失败')
          }
          
          // 5秒后关闭对话框
          setTimeout(() => {
            taskStatusVisible.value = false
          }, 5000)
        }, 10000) // 等待10秒确保视频已完全生成
      } else if (taskStatus.value === 'FAILED') {
        taskProgress.value = 100
        ElMessage.error('视频生成失败')
        
        // 更新列表中的视频状态
        const existingVideo = videoList.value.find(v => v.taskId === taskId.value || v.id === taskId.value)
        if (existingVideo) {
          existingVideo.status = 'FAILED'
          existingVideo.statusMessage = '生成失败'
        }
        
        // 3秒后关闭对话框
        setTimeout(() => {
          taskStatusVisible.value = false
        }, 3000)
      } else {
        // 未知状态，继续轮询
        console.warn('未知的任务状态:', taskStatus.value)
        setTimeout(pollTaskStatus, 10000)
      }
    } else {
      console.error('轮询响应数据为空')
      setTimeout(pollTaskStatus, 10000)
    }
  } catch (error) {
    console.error('轮询任务状态失败:', error)
    
    // 轮询失败，但如果未超过最大次数，仍然继续尝试
    if (pollCount.value < maxPollCount.value) {
      setTimeout(pollTaskStatus, 15000) // 出错后延长等待时间
    } else {
      ElMessage.error('无法获取视频生成状态，请稍后查看历史记录')
      taskStatusVisible.value = false
    }
  }
}

// 从多种可能的响应格式中提取视频URL
const extractVideoUrl = (data) => {
  if (!data) return null
  
  // 尝试多种可能的路径获取URL
  if (data.url) return data.url
  if (data.output?.url) return data.output.url
  if (data.result?.url) return data.result.url
  if (data.video_url) return data.video_url
  if (data.output?.video_url) return data.output.video_url
  if (data.result?.video_url) return data.result.video_url
  
  // 如果都没有找到，尝试查看是否有任务ID，可以构建假URL
  // 这个假URL将在fetchVideoWithAuth中被正确处理
  if (data.taskId) return `/api/media-resources/video/${data.taskId}`
  if (data.task_id) return `/api/media-resources/video/${data.task_id}`
  if (data.output?.task_id) return `/api/media-resources/video/${data.output.task_id}`
  
  return null
}

// 查看生成的视频
const viewGeneratedVideo = () => {
  if (videoList.value.length > 0) {
    // 延迟15秒后尝试预览视频，给服务器更多时间准备视频文件
    ElMessage.info('视频正在准备中，请稍候...')
    setTimeout(() => {
      const video = videoList.value[0]
      
      // 检查视频状态和URL
      if (video.status === 'SUCCEEDED' && video.url) {
        // 已成功且有URL，直接预览
        previewVideo(video)
      } else if (video.taskId) {
        // 没有URL但有任务ID，尝试再次获取视频信息
        getWanxVideoTaskStatus(video.taskId, true).then(response => {
          console.log('获取最新视频状态:', response)
          
          // 尝试从响应中提取URL
          const videoUrl = extractVideoUrl(response.data)
          
          if (videoUrl) {
            // 更新视频对象
            video.url = normalizeVideoUrl(videoUrl)
            video.status = 'SUCCEEDED'
            // 预览视频
            previewVideo(video)
          } else {
            ElMessage.warning('视频可能仍在处理中，请稍后再试')
          }
        }).catch(error => {
          console.error('获取视频状态失败:', error)
          ElMessage.warning('无法获取视频信息，请稍后再试')
        })
      } else {
        ElMessage.warning('视频信息不完整，无法预览')
      }
    }, 15000)
  }
  taskStatusVisible.value = false
}

// 预览视频
const previewVideo = (video) => {
  previewVisible.value = true
  previewLoading.value = true
  previewError.value = false
  previewLoaded.value = false
  previewTitle.value = video.title
  previewItem.value = video
  taskId.value = video.id || video.taskId
  
  if (!video.url && !video.taskId) {
    previewErrorMessage.value = '视频信息不完整，无法预览'
    previewError.value = true
    previewLoading.value = false
    return
  }
  
  // 如果只有taskId没有url，构建一个API URL
  let videoUrl = video.url
  if (!videoUrl && video.taskId) {
    videoUrl = `/api/media-resources/video/${video.taskId}`
    // 更新视频对象的URL
    video.url = videoUrl
  }
  
  // 如果是简单的UUID或ID，转换为API请求格式
  if (!videoUrl.startsWith('http') && !videoUrl.startsWith('/api/')) {
    if (videoUrl.includes('-') || /^[0-9a-f]{8}/.test(videoUrl)) {
      videoUrl = `/api/media-resources/video/${videoUrl}`
    } else {
      videoUrl = `/api/media-resources/video/id/${videoUrl}`
    }
    // 更新视频对象的URL
    video.url = videoUrl
  }
  
  // 增加超时控制
  const timeoutPromise = new Promise((_, reject) => {
    setTimeout(() => reject(new Error('获取视频超时')), 30000)
  })
  
  // 使用Promise.race竞争，如果超时就返回超时错误
  Promise.race([
    fetchVideoWithAuth(videoUrl),
    timeoutPromise
  ]).then(objectUrl => {
    previewUrl.value = objectUrl
    
    // 延迟一点点时间加载视频
    setTimeout(() => {
      if (videoPlayer.value) {
        videoPlayer.value.load()
      }
    }, 100)
  }).catch(error => {
    console.error('加载视频失败:', error)
    previewError.value = true
    
    // 针对不同错误显示不同消息
    if (error.message.includes('超时')) {
      previewErrorMessage.value = '视频加载超时，可能是视频尚未准备好或网络问题'
    } else if (error.message.includes('404')) {
      previewErrorMessage.value = '视频文件不存在，可能正在处理中，请稍后再试'
    } else if (error.message.includes('401')) {
      previewErrorMessage.value = '无权访问视频，请检查登录状态'
    } else {
      previewErrorMessage.value = '加载视频失败: ' + (error.message || '未知错误')
    }
    
    previewLoading.value = false
  })
}

// 使用fetch API获取视频数据，避免直接加载时的认证问题
const fetchVideoWithAuth = async (videoUrl) => {
  // 确保URL格式正确
  let url = videoUrl
  if (!url) throw new Error('视频URL为空')
  
  // 移除现有的时间戳参数
  if (url.includes('?')) {
    url = url.split('?')[0]
  }
  
  // 检查是否是任务ID而不是URL
  if (url.match(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/)) {
    url = `/api/media-resources/video/${url}`
  }
  
  // 修正URL中的域名和端口
  if (url.includes('localhost:8081')) {
    const host = window.location.host
    url = url.replace('localhost:8081', host)
  }
  
  // 确保使用当前站点的协议(http/https)
  if (url.startsWith('/api/')) {
    url = `${window.location.origin}${url}`
  }
  
  // 添加时间戳避免缓存问题
  const timestamp = Date.now()
  url = `${url}?t=${timestamp}`
  
  // 获取认证令牌
  const token = localStorage.getItem('token') || 
              localStorage.getItem('accessToken') || 
              localStorage.getItem('authToken') || 
              localStorage.getItem('jwtToken')
  
  // 创建请求头
  const headers = new Headers()
  if (token) {
    if (token.startsWith('Bearer ')) {
      headers.append('Authorization', token)
    } else {
      headers.append('Authorization', `Bearer ${token}`)
    }
  }
  
  // 重试计数器
  let retryCount = 0
  const maxRetries = 3
  
  async function attemptFetch() {
    try {
      console.log(`尝试获取视频(${retryCount+1}/${maxRetries+1}): ${url}`)
      
      // 使用fetch API请求视频文件
      const response = await fetch(url, {
        method: 'GET',
        headers: headers,
        credentials: 'include' // 包含cookies等认证信息
      })
      
      if (!response.ok) {
        // 处理404错误，可能是视频还未生成完成
        if (response.status === 404 && retryCount < maxRetries) {
          retryCount++
          console.log(`视频文件未找到，${retryCount*2}秒后重试(${retryCount}/${maxRetries})...`)
          // 延迟重试，每次增加等待时间
          await new Promise(resolve => setTimeout(resolve, retryCount * 2000))
          return attemptFetch()
        }
        
        if (response.status === 401) {
          // 尝试刷新令牌
          try {
            const refreshResponse = await axios.post('/api/auth/refresh-token')
            if (refreshResponse.data && refreshResponse.data.token) {
              localStorage.setItem('token', refreshResponse.data.token)
              console.log('认证令牌已刷新，重试获取视频')
              
              // 重置重试计数
              retryCount = 0
              // 使用新令牌重试
              return attemptFetch()
            }
          } catch (refreshError) {
            console.error('刷新令牌失败:', refreshError)
          }
        }
        
        // 检查是否是任务ID而不是真正的视频URL
        if (response.status === 404 && url.includes('/api/media-resources/video/')) {
          const taskId = url.split('/').pop().split('?')[0]
          if (taskId && taskId.match(/^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$/)) {
            // 尝试通过任务状态API获取实际的视频URL
            try {
              console.log('尝试通过任务ID获取视频URL:', taskId)
              const videoResponse = await getWanxVideoTaskStatus(taskId, true)
              const videoUrl = extractVideoUrl(videoResponse.data)
              if (videoUrl && videoUrl !== taskId) {
                console.log('获取到实际视频URL:', videoUrl)
                // 递归调用自身，使用新的URL
                url = normalizeVideoUrl(videoUrl)
                return fetchVideoWithAuth(url)
              }
            } catch (taskError) {
              console.error('通过任务ID获取视频失败:', taskError)
            }
          }
        }
        
        throw new Error(`服务器响应错误: ${response.status} ${response.statusText}`)
      }
      
      // 读取为Blob
      const blob = await response.blob()
      
      // 空白视频检测：如果视频大小特别小，可能是占位文件或空白视频
      if (blob.size < 1000) {
        console.warn('视频文件大小异常小，可能是占位文件或空白视频:', blob.size)
        if (retryCount < maxRetries) {
          retryCount++
          console.log(`视频文件可能未准备好，${retryCount*3}秒后重试(${retryCount}/${maxRetries})...`)
          await new Promise(resolve => setTimeout(resolve, retryCount * 3000))
          return attemptFetch()
        }
      }
      
      // 创建本地Blob URL
      const objectUrl = URL.createObjectURL(blob)
      return objectUrl
    } catch (error) {
      // 如果重试次数未达上限，且是网络错误或404错误，进行重试
      if (retryCount < maxRetries && 
          (error.message.includes('网络错误') || error.message.includes('404'))) {
        retryCount++
        console.log(`获取视频失败，${retryCount*2}秒后重试(${retryCount}/${maxRetries})...`)
        // 延迟重试，每次增加等待时间
        await new Promise(resolve => setTimeout(resolve, retryCount * 2000))
        return attemptFetch()
      }
      
      console.error('获取视频数据失败:', error)
      throw error
    }
  }
  
  return attemptFetch()
}

// 重试加载视频
const retryPreview = async () => {
  previewError.value = false
  previewLoading.value = true
  previewLoaded.value = false
  
  try {
    // 尝试从后端重新获取视频URL
    const currentVideo = videoList.value.find(v => v.url === previewUrl.value || v.id === taskId.value)
    if (currentVideo) {
      // 生成新的API路径
      let videoId = currentVideo.id || currentVideo.taskId
      
      // 如果URL是完整路径，尝试提取ID
      if (currentVideo.url && currentVideo.url.includes('/')) {
        const parts = currentVideo.url.split('/')
        videoId = parts[parts.length - 1].split('?')[0] // 移除查询参数
      }
      
      if (videoId) {
        const videoUrl = `/api/media-resources/video/${videoId}`
        
        // 使用fetch API获取视频
        fetchVideoWithAuth(videoUrl).then(objectUrl => {
          previewUrl.value = objectUrl
          
          // 重置视频播放器
          setTimeout(() => {
            if (videoPlayer.value) {
              videoPlayer.value.load()
            }
          }, 100)
        }).catch(error => {
          throw error
        })
        
        return
      }
    }
    
    // 如果无法获取新URL，尝试重新获取当前URL
    if (previewUrl.value) {
      fetchVideoWithAuth(previewUrl.value.split('?')[0]).then(objectUrl => {
        previewUrl.value = objectUrl
        
        // 重置视频播放器
        setTimeout(() => {
          if (videoPlayer.value) {
            videoPlayer.value.load()
          }
        }, 100)
      }).catch(error => {
        throw error
      })
    } else {
      throw new Error('无法确定视频URL')
    }
  } catch (error) {
    console.error('重试加载视频失败:', error)
    previewError.value = true
    previewErrorMessage.value = '重试加载视频失败: ' + (error.message || '未知错误')
    previewLoading.value = false
  }
}

// 视频组件销毁时释放blob URL
const cleanupBlobUrls = () => {
  if (previewUrl.value && previewUrl.value.startsWith('blob:')) {
    URL.revokeObjectURL(previewUrl.value)
  }
}

// 下载视频
const handleDownload = async (video) => {
  try {
    if (!video.url) {
      ElMessage.warning('视频URL不可用，无法下载')
      return
    }
    
    let videoUrl = video.url
    
    // 检查URL是否为裸视频ID或UUID格式
    if (!videoUrl.startsWith('http') && !videoUrl.startsWith('/api/')) {
      // 如果是简单的UUID或ID，转换为API请求格式
      if (videoUrl.includes('-') || /^[0-9a-f]{8}/.test(videoUrl)) {
        videoUrl = `/api/media-resources/video/${videoUrl}`
      } else {
        videoUrl = `/api/media-resources/video/id/${videoUrl}`
      }
      
      console.log('将视频ID转换为API URL:', videoUrl)
    }
    
    // 检查URL是否为直接本地服务器链接(不带/api前缀)
    if (videoUrl.startsWith('http://localhost:8080/') && !videoUrl.includes('/api/')) {
      // 提取ID部分
      const id = videoUrl.split('/').pop()
      if (id) {
        videoUrl = `/api/media-resources/video/${id}`
        console.log('本地服务器URL转换为API URL:', videoUrl)
      }
    }
    
    // 更新视频对象中的URL，避免下次再转换
    if (videoUrl !== video.url) {
      video.url = videoUrl
    }
    
    // 直接下载URL
    ElMessage.info('开始下载视频...')
    const link = document.createElement('a')
    link.href = videoUrl
    link.download = `${video.title || 'video'}.mp4`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    ElMessage.success('下载请求已发送')
  } catch (error) {
    console.error('下载失败:', error)
    ElMessage.error('下载失败: ' + error.message)
  }
}

// 获取默认视频缩略图
const getDefaultVideoThumbnail = () => {
  // 使用Base64编码的简单占位图，避免网络请求外部资源
  return ''
}

// 处理图片加载错误
const handleImageError = (event, video) => {
  event.target.src = getDefaultVideoThumbnail()
}

// 处理视频加载错误
const handleVideoError = (e) => {
  console.error('视频加载错误:', e)
  previewLoading.value = false
  previewError.value = true
  
  // 根据错误类型设置不同的错误信息
  const video = e.target
  if (video.error) {
    switch (video.error.code) {
      case MediaError.MEDIA_ERR_ABORTED:
        previewErrorMessage.value = '视频加载已中止'
        break
      case MediaError.MEDIA_ERR_NETWORK:
        previewErrorMessage.value = '网络错误导致视频加载失败，可能是认证问题'
        break
      case MediaError.MEDIA_ERR_DECODE:
        previewErrorMessage.value = '视频解码失败，可能格式不支持或文件已损坏'
        break
      case MediaError.MEDIA_ERR_SRC_NOT_SUPPORTED:
        previewErrorMessage.value = '视频格式不受支持或视频无法访问'
        break
      default:
        previewErrorMessage.value = '未知错误导致视频无法播放'
    }
  } else {
    previewErrorMessage.value = '视频加载失败，可能是认证问题或视频不存在'
  }
  
  // 如果是401错误，自动重试
  if (video.error && video.error.code === MediaError.MEDIA_ERR_NETWORK) {
    setTimeout(() => {
      retryPreview()
    }, 1000)
  } else {
    ElMessage.error(previewErrorMessage.value)
  }
}

onMounted(() => {
  if (formData.value.grade) {
    handleStageChange(formData.value.grade)
  }
})

// 在组件销毁时清理资源
onUnmounted(() => {
  cleanupBlobUrls()
})
</script>

<style scoped>
.video-container {
  display: flex;
  max-width: 1600px;
  margin: 0 auto;
  padding: 20px;
  gap: 30px;
}

.main-content {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.selection-panel {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.form-item {
  margin-bottom: 20px;
}

.form-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #333;
}

.action-panel {
  text-align: center;
  margin: 20px 0;
  display: flex;
  justify-content: center;
  gap: 20px;
}

.video-list {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.video-item {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.video-preview {
  flex-shrink: 0;
  margin-right: 20px;
}

.video-wrapper {
  position: relative;
  width: 240px;
  height: 160px;
  overflow: hidden;
  border-radius: 4px;
  border: 1px solid #dcdfe6;
  background-color: #f0f0f0;
}

.video-wrapper .el-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.video-info {
  flex: 1;
}

.video-info h3 {
  margin: 0 0 10px 0;
  color: #333;
}

.video-info p {
  margin: 0 0 10px 0;
  color: #666;
}

.video-meta {
  display: flex;
  gap: 20px;
  color: #999;
  font-size: 14px;
}

.video-actions {
  position: absolute;
  top: 10px;
  right: 10px;
  display: flex;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.video-wrapper:hover .video-actions {
  opacity: 1;
}

.video-preview-dialog :deep(.el-dialog__body) {
  padding: 0;
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 400px;
  background: #f5f7fa;
}

.preview-content {
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center;
  align-items: center;
}

.preview-video {
  max-width: 100%;
  max-height: 600px;
  background: #000;
}

.task-status-dialog :deep(.el-dialog__body) {
  padding: 20px;
}

.task-status-content {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 20px;
}

.task-status-text {
  text-align: center;
  font-size: 16px;
  color: #333;
}

.task-actions {
  margin-top: 10px;
}

.video-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background: #f0f0f0;
  border-radius: 4px;
}

.loading-icon {
  margin-bottom: 10px;
}

.error {
  background: #ffd6d6;
}

.preview-loading, .preview-error {
  width: 100%;
  height: 400px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.preview-error {
  background-color: #fff0f0;
}

.preview-error p {
  margin: 15px 0;
  font-size: 16px;
  color: #f56c6c;
}

.preview-error .el-button {
  margin-top: 10px;
}

.preview-loading .loading-icon {
  font-size: 24px;
  margin-bottom: 10px;
  animation: rotate 2s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
</style>